/*
 *   Copyright 2012, Thomas Kerber
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package milk.jpatch.fileLevel;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import milk.jpatch.Util;

/**
 * Patch denoting that a file gets removed.
 * @author Thomas Kerber
 * @version 1.0.1
 */
public class FileRemove extends FilePatch{
    
    /**
     * The files postfix (i.e. extension)
     */
    public static final String POSTFIX = ".milk.jpatch.frm";
    
    /**
     * Creates.
     * @param name The filename.
     */
    public FileRemove(String name){
        super(name);
    }
    
    @Override
    public void patch(InputStream in, OutputStream out) throws IOException{
        in.close();
        out.close();
    }
    
    @Override
    public void patch(File in, File out) throws IOException{
        // Do nothing.
        // Overridden as the creation of a FileOutputStream would create the
        // file.
    }
    
    @Override
    public void serialize(File root) throws IOException{
        // File has no content. It is identified purely by it's name.
        File outF = new File(root, name + POSTFIX);
        outF.getParentFile().mkdirs();
        outF.createNewFile();
    }
    
    /**
     * 
     * @param f A file.
     * @return Whether the file can be deserialized or not.
     */
    public static boolean canDeserializeAt(File f){
        return f.getName().endsWith(POSTFIX);
    }
    
    /**
     * Deserializes a file in relation to a root dir.
     * @param root The root.
     * @param f The file.
     * @return The deserialization.
     */
    public static FileRemove deserializeAt(File root, File f){
        String relPath = Util.getRelativePath(root, f);
        String name = relPath.substring(0, relPath.indexOf(POSTFIX));
        return new FileRemove(name);
    }
    
}
